package com.imu.purse.admin.controller.business;

import java.util.List;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.imu.common.annotation.SysLog;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.common.validator.group.UpdateGroup;
import com.imu.constant.Constant;
import com.imu.enums.PStatus;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.service.ImuUserService;
import com.imu.purse.modules.sys.entity.SysConfigEntity;
import com.imu.purse.modules.sys.service.SysConfigService;
import com.imu.purse.modules.trade.entity.YmbDetailEntity;
import com.imu.purse.modules.trade.form.YmbChargeForm;
import com.imu.purse.modules.trade.service.YmbDetailService;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 易买宝充值详情表
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-07-02 23:47:18
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@RestController
@RequestMapping("ymbdetail")
public class YmbDetailController extends com.imu.purse.modules.sys.controller.AbstractController
{
	/****
	 * 查询易买宝充值详情表
	 * @param params
 	 * @date 2018-07-02 23:47:18
	 * @return
	 */
	@SysLog("查询易买宝充值详情表")
	@GetMapping("/list")
	@RequiresPermissions("ymbdetail:list")
	public R list(@RequestParam Map<String, Object> params)
	{
		R r = R.ok();
		if(CollectionUtils.isEmpty(params)) return r;
		
		YmbDetailEntity dto = BeanUtil.mapToBean(params, YmbDetailEntity.class, true);
		if("".equals(dto.getPhone())) dto.setPhone(null);
		List<YmbDetailEntity> dtos = service.queryList(dto);
		if(CollectionUtils.isEmpty(dtos)) return r;
		
		return r.put("page", new PageInfo<YmbDetailEntity>(dtos));
	}
	
	/****
	 * 根据ID查询易买宝充值详情表
	 * @param id
 	 * @date 2018-07-02 23:47:18
	 * @return
	 */
	@SysLog("根据ID查询易买宝充值详情表")
	@GetMapping("/info/{id}")
	@RequiresPermissions("ymbdetail:info")
	public R info(@PathVariable("id") Long id)
	{
		return R.ok().put("dto", service.findById(id));
	}
	
	/****
	 * 新增易买宝充值详情表
	 * @param dto
 	 * @date 2018-07-02 23:47:18
	 * @return
	 */
	@SysLog("新增易买宝充值详情表")
	@PostMapping("/save")
	@RequiresPermissions("ymbdetail:save")
	public R save(@RequestBody YmbDetailEntity dto)
	{
		ValidatorUtils.validateEntity(dto, AddGroup.class);
		service.save(dto);
		return R.ok();
	}

	/****
	 * 新增易买宝充值详情表
	 * @param dto
 	 * @date 2018-07-02 23:47:18
	 * @return
	 */
	@SysLog("充值易买宝")
	@PutMapping("/charge")
	@RequiresPermissions("ymbdetail:charge")
	public R charge(@RequestBody YmbChargeForm form)
	{
		ValidatorUtils.validateEntity(form, AddGroup.class);
		
		if(null == form || 0 == form.getMoney().intValue())
        {
			return  R.error(612, "充值金额不能为0");
        }
		
		//根据id获取该用户的手机号码
        ImuUserEntity user = userService.findById(form.getUserId());
        if(null == user || StrUtil.isBlank(user.getPhone())){
            return R.error(ErrorDesc.GET_USER_ERR.getCode(), ErrorDesc.GET_USER_ERR.getMsg());
        }
		
		YmbDetailEntity entity = new YmbDetailEntity();
		com.xiaoleilu.hutool.bean.BeanUtil.copyProperties(form, entity);
		entity.setCreateUser(getUserId());
		entity.setUpdateUser(getUserId());
		//易买宝信息归集
		SysConfigEntity config = sysConfigService.findByKey(Constant.PRI_USER_KEY);
        Long userId = 0l;
        if(null != config && StrUtil.isNotBlank(config.getValue()))
        {
        	try {
				userId = Long.valueOf(config.getValue());
        	} 
        	catch (Exception e) { }
        }
        
        if(0 >= userId) return R.error(611, "收款信息不存在,请联系管理员");
        
		service.charge("charge:ymb", entity, true, userId);
		return R.ok();
	}
	
	/****
	 * 修改易买宝充值详情表
	 * @param dto
 	 * @date 2018-07-02 23:47:18
	 * @return
	 */
	@SysLog("修改易买宝充值详情表")
	@PostMapping("/update")
	@RequiresPermissions("ymbdetail:update")
	public R update(@RequestBody YmbDetailEntity dto)
	{
		ValidatorUtils.validateEntity(dto, UpdateGroup.class);
		if(null == dto.getOrderState() || 0 == dto.getOrderState())
        {
			return  R.error(613, "状态不能为空");
        }
		
		YmbDetailEntity entity = service.findById(dto.getId());
		if(null == entity || null == entity.getOrderState() || PStatus.Create.getType() != entity.getOrderState().intValue()) //审核通过 增加金额写记录
		{
            return R.error(ErrorDesc.GET_USER_ERR.getCode(), ErrorDesc.GET_USER_ERR.getMsg());
		}
		else if(0 >= entity.getMoney().intValue())
        {
			return  R.error(612, "充值金额不能为0");
        }

		//易买宝信息归集
		SysConfigEntity config = sysConfigService.findByKey(Constant.PRI_USER_KEY);
        Long userId = 0l;
        if(null != config && StrUtil.isNotBlank(config.getValue()))
        {
        	try {
				userId = Long.valueOf(config.getValue());
        	} 
        	catch (Exception e) { }
        }

        if(0 >= userId) return  R.error(611, "收款信息不存在,请联系管理员");
		
        entity.setOrderState(dto.getOrderState());
        entity.setDescription(dto.getDescription());
        entity.setUpdateUser(this.getUserId());
		service.charge("YMB:" + this.getUserId(), entity, false, userId);
		return R.ok();
	}
	
	/****
	 * 删除易买宝充值详情表
	 * @param ids
 	 * @date 2018-07-02 23:47:18
	 * @return
	 */
	@SysLog("删除易买宝充值详情表")
	@PutMapping("/delete")
	@RequiresPermissions("ymbdetail:delete")
	public R delete(@RequestBody String[] ids)
	{
		service.delete(ids);
		return R.ok();
	}

	@Autowired
	private YmbDetailService service;
	
	@Autowired
	private ImuUserService userService;

    @Autowired
    private SysConfigService sysConfigService;
}
